#pragma once 
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<functional>
#include "Log.hpp"
#include "InetAddr.hpp"
enum {
    SOCK_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};
const static int defaultfd = -1;

using func_t = std::function<std::string(const std::string&,bool& ok)>;
class UdpServer
{
    private:
        int _sockfd;
        uint16_t _port;//服务器所使用的端口号
        bool _isruning;
        func_t _func;
    public:
        UdpServer(uint16_t port,func_t func)
        :_sockfd(defaultfd)
        ,_port(port)
        ,_isruning(false)
        ,_func(func)
        {}
        void InitServer()
        {
            //1. 创建套接字
            _sockfd = socket(AF_INET,SOCK_DGRAM,0);

            if(_sockfd < 0)
            {

                LOG(ERROR,"socket error, %s, %d",strerror(errno),errno);
                exit(SOCK_ERROR);
            }
            LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);

            //2. 填充socketaddr_in 结构体
            struct sockaddr_in local;// struct sockaddr_in 系统提供的数据类型。
            bzero(&local,sizeof(local));//== memset(&server, 0, sizeof(server));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);// port要经过网络传输给对面，先到网络，_port：主机序列-> 主机序列，转成网络序列
            // a. 字符串风格的点分十进制的IP地址转成 4 字节IP
            // b. 主机序列，转成网络序列
            // in_addr_t inet_addr(const char *cp) -> 同时完成 a & b
            // local.sin_addr.s_addr = inet_addr(_ip.c_str()); // "192.168.3.1" -> 字符串风格的点分十进制的IP地址 -> 4字节IP
            local.sin_addr.s_addr = INADDR_ANY;
            //绑定 socket 和 网络通信(ip + port)
            int n = bind(_sockfd , (struct sockaddr*)&local,sizeof(local));
            if(n < 0)
            {
                LOG(FATAL,"bind error,%s, %d",strerror(errno),errno);
                exit(BIND_ERROR);
            }
            LOG(INFO,"socket bind success");
        }
        void Start()
        {
            // 一直运行，直到管理者不想运行了， 服务器都是死循环
            // UDP是面向数据报的协议
            _isruning = true;
            while(true)
            {
                char buffer[1024];
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                //1. 接收数据ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,struct sockaddr *src_addr, socklen_t *addrlen);
                ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer)-1, 0, (struct sockaddr*)&peer,&len); //预留一个位置放置0
                if(n > 0)
                {
                    buffer[n] = 0;
                    InetAddr addr(peer);
                    LOG(DEBUG,"get message from [%s:%d]: %s", addr.Ip().c_str(), addr.Port(), buffer);
                    //ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen);
                    bool ok;
                    std::string reponse = _func(buffer,ok);// 将请求，回调出去，在外部进行数据处理
                    sendto(_sockfd,reponse.c_str(),reponse.size(),0, (struct sockaddr*)&peer,len);
                }
            }
            _isruning = false;
        }

};
